package com.syh.jn.scm.service.impl.downstream.purchase;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.syh.core.ddd.event.annotation.DomainEventHandle;
import com.syh.core.ddd.infrastructure.repository.AggregateRepository;
import com.syh.core.ddd.service.AbstractServiceImpl;
import com.syh.jn.scm.domain.downstream.entity.purchase.DownPurchaseOrder;
import com.syh.jn.scm.domain.downstream.event.DownPurchaseOrderEvent;
import com.syh.jn.scm.domain.support.entity.History;
import com.syh.jn.scm.domain.support.repository.HistoryRepository;
import com.syh.jn.scm.dto.downstream.purchase.DownPurchaseOrderVo;
import com.syh.jn.scm.dto.supplier.sale.SaleOrderVo;
import com.syh.jn.scm.dto.support.HistoryDto;
import com.syh.jn.scm.dto.support.HistoryVo;
import com.syh.jn.scm.service.api.downstream.purchase.DownPurchaseOrderHistoryService;
import com.syh.jn.scm.service.api.downstream.purchase.DownPurchaseOrderService;
import com.syh.jn.scm.service.api.supplier.sale.SaleOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


/**
 * Created by soci.song on 2019/1/18.
 */
@Service
@Transactional
public class DownPurchaseOrderHistoryServiceImpl extends AbstractServiceImpl<HistoryDto, HistoryDto, HistoryVo, History, Long> implements DownPurchaseOrderHistoryService {

  @Resource(name = "downPurchaseHistoryRepositoryImpl")
  private HistoryRepository downPurchaseHistoryRepository;
  @Autowired
  private DownPurchaseOrderService downPurchaseOrderService;

  @Override
  protected AggregateRepository<History, Long> getAggregateRepository() {
    return this.downPurchaseHistoryRepository;
  }

  @Override
  public Long save(HistoryDto dto) {
    DownPurchaseOrderVo downPur = downPurchaseOrderService.getById(dto.getOriginalId());
    dto.buildHistory(JSONObject.parseObject(JSON.toJSONString(downPur)));
    return downPurchaseHistoryRepository.add(new History(dto));
  }

  /**
   * 消费者：监听下游采购单删除（删除该单的历史记录）
   *
   * @param downPurchaseOrder
   */
  @DomainEventHandle(DownPurchaseOrderEvent.DOWN_PURCHASE_ORDER_DESTORY)
  protected void handlePurchaseOrderDestory(DownPurchaseOrder downPurchaseOrder) {
    this.downPurchaseHistoryRepository.deleteHistorysByOriginalId(downPurchaseOrder.getId());
  }
}
